<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI简历分析</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 在header或导航区域添加 -->
    <div class="flex justify-end">
        <!-- 用户角色信息 -->
        <span class="text-sm text-gray-700">
            您好，<a href="/api/account" id="user-role-display" class="user-role-link text-blue-500 font-medium">加载中...</a>
        </span>
        <a href="#" onclick="handleLogout()"
           class="text-neutral-dark hover:text-primary transition-custom">
            <i class="fa fa-sign-out mr-1"></i>退出登录
        </a>
    </div>
</head>
<body class="bg-gray-50">
<div class="max-w-4xl mx-auto p-4">
    <div class="bg-white rounded-lg shadow-md p-6">
        <h1 class="text-2xl font-bold mb-6">AI简历分析</h1>

        <!-- 聊天界面 -->
        <div id="chat-container" class="mb-6 h-96 overflow-y-auto p-4 border border-gray-200 rounded-lg">
            <!-- 消息会动态添加到这里 -->
            <div class="flex items-start mb-4">
                <div class="bg-blue-500 text-white p-2 rounded-full mr-3">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-blue-100 p-3 rounded-lg rounded-tl-none max-w-[80%]">
                    <p>你好！我是AI简历分析助手，很高兴为你服务。有什么我可以帮助你的吗？</p>
                    <p class="text-xs text-gray-500 mt-1">今天 09:30</p>
                </div>
            </div>
            <div class="flex items-start mb-4">
                <div class="bg-blue-500 text-white p-2 rounded-full mr-3">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-blue-100 p-3 rounded-lg rounded-tl-none max-w-[80%]">
                    <p>为了更好地分析简历，你可以上传简历文件（PDF或Word格式），我会帮你提取和分析关键信息。</p>
                    <p class="text-xs text-gray-500 mt-1">今天 09:30</p>
                </div>
            </div>
            <!-- 红色方框位置的输入区域 -->

        </div>


        <!-- 文件上传区域 -->
        <div class="mb-4">
            <input type="file" id="resume-file" accept=".pdf,.doc,.docx" class="mb-2">
            <div id="file-name" class="text-sm text-gray-600 mb-2"></div>
            <button id="upload-btn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">
                <i class="fa fa-upload mr-1"></i> 上传简历
            </button>
            <div class="input-group mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">请输入您的反馈或问题：</label>
                <div class="flex space-x-2">
                    <input type="text" id="user-input" placeholder="请先上传简历，分析之后再询问哦~"
                           class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" disabled>
                    <button id="submit-btn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors" disabled>
                        提交
                    </button>
                </div>
                <p class="text-xs text-gray-500 mt-2">您可以在这里输入后续问题或对分析结果的反馈</p>
            </div>
        </div>

        <!-- 加载状态 -->
        <div id="loading" class="hidden text-blue-500 mb-4">
            <i class="fa fa-spinner fa-spin mr-1"></i> 正在分析简历...
        </div>

        <!-- 错误信息 -->
        <div id="error-message" class="hidden text-red-500 mb-4"></div>
    </div>

    <!--隐藏域存储 -->
    <input type="hidden" id="token" th:value="${token}">
</div>

<script>


    // 全局状态标记
    //let isResumeUploaded = false;
    // 获取DOM元素
    const fileInput = document.getElementById('resume-file');
    const fileNameDisplay = document.getElementById('file-name');
    const uploadBtn = document.getElementById('upload-btn');
    const chatContainer = document.getElementById('chat-container');
    const loadingIndicator = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    let token = localStorage.getItem("token");
    const userInput = document.getElementById('user-input');
    const submitBtn = document.getElementById('submit-btn');
    //从隐藏域获取
    // const token = document.getElementById('token').value;
    // localStorage.setItem("token", token);
    // 显示选中的文件名
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            fileNameDisplay.textContent = `已选择: ${e.target.files[0].name}`;
        } else {
            fileNameDisplay.textContent = '';
        }
    });

    // 上传文件并处理响应
    uploadBtn.addEventListener('click', async () => {
        const file = fileInput.files[0];
        if (!file) {
            showError('请先选择一个文件');
            return;
        }
        // 验证文件类型
        const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        if (!allowedTypes.includes(file.type)) {
            showError('请上传PDF或Word格式的文件');
            return;
        }
        try {
            // 显示加载状态
            showLoading(true);
            clearError();
            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);
            // 发送文件到后端API
            const response = await fetch('http://localhost:8080/api/resume/upload', {
                method: 'POST',
                headers: {
                    'Authorization': token
                },
                body: formData,
                // 注意：上传文件时不要设置Content-Type为application/json
                // 浏览器会自动设置正确的Content-Type和边界
            });
            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }
            console.log("response"+response);
            // 解析JSON响应
            const result = await response.json();
            console.log("后端传输的ai回答"+result.data);
            //解除对话框禁用
            onResumeUploadSuccess()
            // 隐藏加载状态
            showLoading(false);
            // 显示上传成功的消息
            addMessageToChat('系统', `已上传文件: ${file.name}`, new Date());
            // 显示分析结果
            // const formattedContent = formatAnalysisContent(result.data)
            // console.log("分析结果"+formattedContent)
            // addMessageToChat('AI简历分析', formattedContent, new Date())
            displayAnalysisResult(result.data);
        } catch (error) {
            showLoading(false);
            showError(`上传失败: ${error.message}`);
            console.error('上传错误:', error);
        }
    });

    // 显示分析结果
    function displayAnalysisResult(data) {
        let resultHtml = `
                <p class="font-semibold">简历分析结果：</p>
                <p><strong>姓名：</strong>${data.name || '未提供'}</p>
            `;

        // 添加联系方式
        if (data.contact) {
            resultHtml += `
                    <p><strong>联系方式：</strong></p>
                    <ul class="list-disc ml-5">
                        <li>电话：${data.contact.phone || '未提供'}</li>
                        <li>邮箱：${data.contact.email || '未提供'}</li>
                    </ul>
                `;
        }

        // 添加教育经历
        if (data.education && data.education.length > 0) {
            resultHtml += `
                    <p class="mt-2"><strong>教育经历：</strong></p>
                    <ul class="list-disc ml-5">
                `;

            data.education.forEach(edu => {
                resultHtml += `
                        <li>
                            <p>${edu.school} ${edu.major}</p>
                            <p>${edu.time}</p>
                        </li>
                    `;
            });

            resultHtml += `</ul>`;
        }

        // 添加工作经历
        if (data.workExperience && data.workExperience.length > 0) {
            resultHtml += `
                    <p class="mt-2"><strong>工作经历：</strong></p>
                `;

            data.workExperience.forEach(exp => {
                resultHtml += `
                        <div class="ml-5 mt-1">
                            <p><strong>${exp.projectName}</strong> ${exp.time}</p>
                            <p>角色：${exp.role}</p>
                            <p>技术栈：${exp.techStack}</p>
                            ${exp.responsibilities ? `
                                <p>职责：</p>
                                <ul class="list-disc ml-5">
                                    ${exp.responsibilities.map(resp => `<li>${resp}</li>`).join('')}
                                </ul>
                            ` : ''}
                        </div>
                    `;
            });
        }

        // 将结果添加到聊天窗口
        addMessageToChat('AI简历分析', resultHtml, new Date());
    }

    // 向聊天窗口添加消息
    function addMessageToChat(sender, content, timestamp) {
        const timeString = timestamp.toLocaleTimeString();
        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex items-start mb-4';
        messageDiv.innerHTML = `
                <div class="bg-blue-500 text-white p-2 rounded-full mr-3">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-blue-100 p-3 rounded-lg rounded-tl-none max-w-[80%]">
                    ${content}
                    <p class="text-xs text-gray-500 mt-1">${timeString}</p>
                </div>
            `;
        chatContainer.appendChild(messageDiv);
        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 显示/隐藏加载状态
    function showLoading(show) {
        loadingIndicator.style.display = show ? 'block' : 'none';
    }

    // 显示错误信息
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
    }

    // 清除错误信息
    function clearError() {
        errorMessage.textContent = '';
        errorMessage.style.display = 'none';
    }

    function handleLogout() {
        // 从本地缓存获取token
        const token = localStorage.getItem('token');

        if (token && confirm('确定要退出登录吗？')) {
            // 方式1：跳转到退出URL并携带token
            window.location.href = '/api/logout?token=' + encodeURIComponent(token);

        }
    }

    // 页面加载完成后获取当前用户信息
    document.addEventListener('DOMContentLoaded', function() {
        fetchCurrentUser();
    });

    // 获取当前用户信息
    async function fetchCurrentUser() {
        try {
            let token = localStorage.getItem("token")
            const response = await fetch('/api/currentUser', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                }
            });

            const result = await response.json();
            if (result.code === '200' && result.data) {
                // 将角色信息绑定到页面上的user-role-display元素
                document.getElementById('user-role-display').textContent = result.data.role;
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            document.getElementById('user-name').textContent = '未登录用户';
            document.getElementById('user-role').textContent = '游客';
        }
    }


    // 后端返回的字符串内容

    // 格式化函数
    function formatAnalysisContent(content) {
        let formatted = content;

        // 处理评分
        formatted = formatted.replace(/(\d+\/100)/g, '<span class="score-badge">$1</span>');

        // 处理标题
        formatted = formatted.replace(/### (.+)/g, '<h3>$1</h3>');
        formatted = formatted.replace(/## (.+)/g, '<h2>$1</h2>');
        formatted = formatted.replace(/# (.+)/g, '<h1>$1</h1>');

        // 处理粗体
        formatted = formatted.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');

        // 处理分割线
        formatted = formatted.replace(/---/g, '<div class="divider"></div>');

        // 处理列表
        formatted = formatted.replace(/\n\*   /g, '\n<li>');
        formatted = formatted.replace(/(<li>.*)(?=\n(?!<li>))/gs, '<ul>$1</ul>');

        // 处理数字列表
        formatted = formatted.replace(/\n\d\.   /g, '\n<li>');
        formatted = formatted.replace(/(<li>.*)(?=\n(?!<li>))/gs, '<ol>$1</ol>');

        // 处理结论和建议
        formatted = formatted.replace(/(结论：.+?)(?=\n\n|$)/s, '<div class="conclusion-box">$1</div>');
        formatted = formatted.replace(/(建议：.+?)(?=\n\n|$)/s, '<div class="conclusion-box">$1</div>');

        // 处理技术标签
        //formatted = formatted.replace(/(集合|多线程|Lambda|Stream API|SSM|SpringBoot|MySQL|事务|索引|锁|Redis|分布式session|分布式锁|Redisson|缓存穿透|雪崩|击穿|RabbitMQ|应用解耦|SpringCloud Alibaba|Nacos|Feign|Gateway|Docker|工厂|代理|策略|模板方法|Spring Security|Vue)/g, '<span class="tech-tag">$1</span>');

        // 保持换行
        formatted = formatted.replace(/\n/g, '<br>');
        return formatted;
    }

    // 初始化页面
    // document.addEventListener('DOMContentLoaded', function() {
    //     const formattedContent = formatAnalysisContent(aiResponse);
    //     console.log(formattedContent)
    //     addMessageToChat('AI简历分析', formattedContent, new Date())
    //     document.querySelector('main').innerHTML = formattedContent;
    // });

    // 上传简历成功的回调函数
    function onResumeUploadSuccess() {
        //isResumeUploaded = true;

        // 启用输入框和提交按钮
        userInput.disabled = false;
        submitBtn.disabled = false;

        // 更新placeholder提示
        userInput.placeholder = "请输入您的问题...";

        // 添加动画效果
        // userInput.classList.add('animate-pulse');
        // setTimeout(() => {
        //     userInput.classList.remove('animate-pulse');
        // }, 1000);
    }

    //点击提交
    submitBtn.addEventListener('click', async () => {
        // 获取用户输入的问题
        const question = userInput.value.trim();
        // 清空输入框
        userInput.value = '';
        const token = localStorage.getItem('token');
        // 准备请求参数
        const params = new URLSearchParams();
        params.append('question', question);
        showLoading(true);
        // 调用后端API
        const response = await fetch('http://localhost:8080/api/resume/ask', {
            method: 'POST',
            headers: {
                'Authorization': token
            },
            body: params
        })
        const result = await response.json();
        showLoading(false);
        if (result.code === '200'){
            const formattedContent = formatAnalysisContent(result.data)
            console.log("分析结果"+formattedContent)
            addMessageToChat('AI简历分析', formattedContent, new Date())
        }
    });

</script>
</body>
</html>
